import uuid

from django.conf import settings
from rest_framework import serializers
from rest_framework.exceptions import APIException

from apps.libs.al_pay import GATEWAY, alipay
from apps.models import Order, HouseKeeping, OrderDetail, Address, User


class OrderPaySerializer(serializers.ModelSerializer):
    # order_details = serializers.PrimaryKeyRelatedField(many=True, queryset=OrderDetail.objects.all())
    class Meta:
        model = Order
        fields=['out_trade_no']


    def _get_out_trade_no(self):
        # 使用uuid生成--》后期会有别的生成id的方案：1 效率高 2 不重复 3 单调递增趋势 4 在分布式节点中不会重复
        out_trade_no = str(uuid.uuid4()).replace('-', '')
        return out_trade_no

    # def _get_user(self):
    #     # 获取用户得实例
    #     # request = self.context.get('request')
    #     # username = request.data.get('username')
    #     # user = User.objects.get(username=username)
    #     # print('user-----',self.context.get('request').user)
    #     return self.context.get('request').user

    def _get_pay_url(self, out_trade_no, total_amount, subject):
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=out_trade_no,
            total_amount=float(total_amount),  # 只有生成支付宝链接时，不能用Decimal
            subject=subject,
            return_url=settings.RETURN_URL,  # get 回调 --》前端
            notify_url=settings.NOTIFY_URL,  # post 回调--》后端
        )
        pay_url = GATEWAY + '?' + order_string
        # 将支付链接存入，传递给views
        self.context['pay_url'] = pay_url

    def _before_create(self, attrs, out_trade_no):
        # attrs ={'courses':[对象,],'total_amount':0.1,'subject':课程名,'pay_type':1}
        # attrs['user'] = user
        attrs['out_trade_no'] = out_trade_no

    def validate(self, attrs):
        requeust=self.context.get('request')
        id=requeust.query_params.get('id')
        # print(id)
        orderdetail=OrderDetail.objects.get(id=id)
        total_amount=orderdetail.total_amount
        housekeeping=orderdetail.housekeeping
        count=orderdetail.count
        user=orderdetail.user
        attrs['user'] = user
        attrs['count'] = count
        attrs['housekeeping']=housekeeping
        attrs['status'] = 3
        # print(total_amount)
        # 2 生成订单号--》唯一的--》
        out_trade_no = self._get_out_trade_no()
        title = requeust.query_params.get('title')
        attrs['subject']=title
        attrs['total_amount']=total_amount
        print('subject',attrs.get('subject'))
        # 3 获取支付人 --》当前登录用户
        # user = self._get_user()
        # 4 获取支付链接--》
        self._get_pay_url(out_trade_no, total_amount, attrs.get('subject'))
        # 5 入库(两个表)的信息准备
        self._before_create(attrs, out_trade_no)
        return attrs

